﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Collections;
using System.Text.RegularExpressions;

namespace week3
{
    class Program
    {
        static Hashtable ht = new Hashtable(StringComparer.OrdinalIgnoreCase);
        static string DeleteComments(string s) //去掉以//开始的注释
        {
            if (s == "")
            {
                return s;
            }
            int pos = s.IndexOf("//");
            if (pos < 0) return s;
            return s.Substring(0, pos);
        }

        static int Linestat(string line,int wordnum,bool f)
        {
            int num = wordnum;
            string[] wordArr = null;
            line = Regex.Replace(line, @"[\p{P}*]", " ", RegexOptions.Compiled);//去除标点
            wordArr = line.Split(' ');
            foreach (string s in wordArr)
            {
                if (s == "") continue;
                num++;
                string w = s.ToLower();
                //将单词加入哈希表
                if (f)
                {
                    if (ht.ContainsKey(w))
                    {
                        ht[w] = Convert.ToInt32(ht[w]) + 1;
                    }
                    else
                    {
                        ht.Add(w, 1);
                    }
                }
            }
            return num;
　　}

        static void Main(string[] args)
        {
            FileStream fin = new FileStream("CopyFileAddLineNumber.cs",
            FileMode.Open, FileAccess.Read);
            FileStream fout = new FileStream("CopyFileAddLineNumber.txt",
            FileMode.Create, FileAccess.Write);
            StreamReader brin = new StreamReader(fin, System.Text.Encoding.Default);
            StreamWriter brout = new StreamWriter(fout, System.Text.Encoding.Default);
            int cnt1 = 0, cnt2 = 0;
            int num1 = 0,num2 = 0;
            for (string s = brin.ReadLine(); s != null; s = brin.ReadLine())
            {
                cnt1++;
                cnt2++;
                num1 =  Linestat(s,num1,false);
                s = DeleteComments(s);
                if (s == "")
                {
                    cnt2--;
                }
            else
                {
                    num2 = Linestat(s, num2, true);                      
                }
                
            }
            Console.WriteLine("格式化前：原始行数为：" + cnt1 + "\t单词数为：" + num1);
            Console.WriteLine("格式化后：原始行数为：" + cnt2 + "\t单词数为：" + num2);
            Console.WriteLine("格式化后各单词数目（转化为小写）：");
            ArrayList keysList = new ArrayList(ht.Keys);
            keysList.Sort();
            foreach(object item in keysList)
　　      {
                Console.WriteLine((string)item + ":" + ht[item].ToString());
　       　}
            brin.Close();
            brout.Close();
            Console.ReadLine();
        }
    }
}
